package com.example.myapplication.rxjava;

import android.os.Bundle;
import android.os.Looper;

import androidx.annotation.Nullable;

import com.example.myapplication.base.BaseActivity;
import com.example.myapplication.rxjava.weather.NowWeatherResponse;
import com.example.myapplication.rxjava.weather.version1.QWeatherApi1;
import com.example.myapplication.rxjava.weather.version2.QWeatherApi2;
import com.example.myapplication.rxjava.weather.version3.QWeatherApi3;
import com.example.myapplication.rxjava.weather.version4.QWeatherApi4;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.RealInterceptorChain;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by ymz0427 on 2021/7/17
 */
public class RxJavaActivity extends BaseActivity {

    private List<Disposable> list = new ArrayList<>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        //地区的id
        String location = "101010100";
        //替换成自己在和风天气申请的key,
        String key = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~";

        queryNow4(key);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (Disposable disposable : list) {
            if (disposable != null && !disposable.isDisposed()) {
                disposable.dispose();
            }
        }
    }

    private void queryNow1(String key) {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("https://devapi.qweather.com")
                .build();
        QWeatherApi1 api1 = retrofit.create(QWeatherApi1.class);
        api1.queryNow(key, "101010100").enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(@NotNull Call<ResponseBody> call, @NotNull retrofit2.Response<ResponseBody> response) {
                try {
                    System.out.println(response.code());
                    System.out.println("onResponse(" + response.body().string());
                    System.out.println(Looper.myLooper());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                System.out.println("onFailure(" + t.getMessage());
            }
        });
    }

    private void queryNow2(String key) {
        OkHttpClient client = new OkHttpClient.Builder()
                //连接超时时间
                .connectTimeout(10, TimeUnit.SECONDS)
                //读超时时间
                .readTimeout(10, TimeUnit.SECONDS)
                //写超时时间
                .writeTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
                    @NotNull
                    @Override
                    public Response intercept(@NotNull Chain chain) throws IOException {
                        //统一添加接口需要的key
                        RealInterceptorChain realInterceptorChain = (RealInterceptorChain) chain;
                        Request request = realInterceptorChain.request();

                        HttpUrl.Builder builder = request.url().newBuilder();
                        builder.addQueryParameter("key", key);

                        return chain.proceed(request.newBuilder().url(builder.build()).build());
                    }
                })
                .build();
        Retrofit retrofit = new Retrofit.Builder().baseUrl("https://devapi.qweather.com")
                .client(client)
                .build();
        QWeatherApi2 api2 = retrofit.create(QWeatherApi2.class);
        api2.queryNow("101010100").enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(@NotNull Call<ResponseBody> call, @NotNull retrofit2.Response<ResponseBody> response) {
                try {
                    System.out.println(response.code());
                    System.out.println("onResponse(" + response.body().string());
                    System.out.println(Looper.myLooper());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                System.out.println("onFailure(" + t.getMessage());
            }
        });
    }

    private void queryNow3(String key) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
                    @NotNull
                    @Override
                    public Response intercept(@NotNull Chain chain) throws IOException {
                        //添加key
                        RealInterceptorChain realInterceptorChain = (RealInterceptorChain) chain;
                        Request request = realInterceptorChain.request();

                        HttpUrl.Builder builder = request.url().newBuilder();
                        builder.addQueryParameter("key", key);

                        return chain.proceed(request.newBuilder().url(builder.build()).build());
                    }
                })
                .build();

        Retrofit retrofit = new Retrofit.Builder().baseUrl("https://devapi.qweather.com")
                //使用gson进行json到model的转换
                .addConverterFactory(GsonConverterFactory.create())
                //okhttp进行数据实际请求
                .client(client)
                .build();
        QWeatherApi3 api3 = retrofit.create(QWeatherApi3.class);
        api3.queryNow("101010100").enqueue(new Callback<NowWeatherResponse>() {
            @Override
            public void onResponse(Call<NowWeatherResponse> call, retrofit2.Response<NowWeatherResponse> response) {
                System.out.println(response.body());
            }

            @Override
            public void onFailure(Call<NowWeatherResponse> call, Throwable t) {
                System.out.println("onFailure(" + t.getMessage());
            }
        });
    }


    private void queryNow4(String key) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
                    @NotNull
                    @Override
                    public Response intercept(@NotNull Chain chain) throws IOException {
                        //添加key
                        RealInterceptorChain realInterceptorChain = (RealInterceptorChain) chain;
                        Request request = realInterceptorChain.request();

                        HttpUrl.Builder builder = request.url().newBuilder();
                        builder.addQueryParameter("key", key);

                        return chain.proceed(request.newBuilder().url(builder.build()).build());
                    }
                })
                .build();

        Retrofit retrofit = new Retrofit.Builder().baseUrl("https://devapi.qweather.com")
                //使用gson进行json到model的转换
                .addConverterFactory(GsonConverterFactory.create())
                //使用rxjava管理数据的请求与线程切换
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                //okhttp进行数据实际请求
                .client(client)
                .build();

        QWeatherApi4 api4 = retrofit.create(QWeatherApi4.class);
        api4.queryNow("101010100")
                .map(nowWeatherResponse -> {
                    // 这里是io线程，可以进行复杂耗时的操作
                    System.out.println("线程：" + Thread.currentThread());
                    return nowWeatherResponse;
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(nowWeatherResponse -> {
                    // 这里已经是主线程了，
                    System.out.println("线程：" + Thread.currentThread());
                    return nowWeatherResponse;
                })
                .subscribe(new Observer<NowWeatherResponse>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        list.add(d);
                    }

                    @Override
                    public void onNext(@NonNull NowWeatherResponse weatherResponse) {
                        System.out.println("onNext:" + weatherResponse);
                        System.out.println("onNext(线程：" + Thread.currentThread());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        System.out.println("onError:" + e.getMessage());
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
